﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using System.Xml;
using System.Xml.Serialization;



namespace Interface
{
   

    class Client
    {

        public String username;
        public String screenname;
        public String password;
        public String server;

        public Client(){
            /*var wrapper = new VersionRetrieverWrapper();
            wrapper.Request = new InheritedRequestA();
            wrapper.Request.Member = "Request";
            wrapper.Response = new InheritedResponseA();
            wrapper.Response.Member = "Response";
            Console.WriteLine(Save(wrapper));
                     
            */
            
        }

        //serialize a get users request(test only)
        public String test()
        {
            var wrapper = new VersionUsers();
            
            wrapper.users.Add(new user());
            wrapper.users.Add(new user());
            wrapper.users[0].fullname = "one";
            wrapper.users[1].fullname = "two";
            TextWriter textWriter;
            textWriter = new StreamWriter(@"C:\Documents and Settings\info_seb\Bureau\testurls.xml");
            String ret = Save(wrapper);
            textWriter.Write(ret);
            textWriter.Close();
            return ret;
        }

        //serialize a get moves request(test only)
        public String test2()
        {
            var wrapper = new VersionGetMoves();

            wrapper.moves = new moves();
            wrapper.moves.movess.Add( new move());
            wrapper.moves.board = "board test";
            wrapper.moves.total = 30;
            wrapper.moves.movess[0].column = 1;
            wrapper.moves.movess[0].row = 2;
            wrapper.moves.movess[0].seq = 3;
            wrapper.moves.movess.Add(new move());

            //wrapper.moves.
            TextWriter textWriter;
            textWriter = new StreamWriter(@"C:\Documents and Settings\info_seb\Bureau\testmoves.xml");
            String ret = Save(wrapper);
            textWriter.Write(ret);
            textWriter.Close();
            return ret;
        }

        //serialize a get board request(test only)
        public String test3()
        {
            var wrapper = new VersionGetBoard();

            wrapper.Board = new BoardToPlay();
            //wrapper.Board.moves=new moves();
            wrapper.Board.moves.Add(new move());
          
            wrapper.Board.moves[0].column = 1;
            wrapper.Board.moves[0].row = 2;
            wrapper.Board.moves[0].seq = 3;
            wrapper.Board.moves.Add(new move());

            wrapper.Board.creation_date.val = "now";
            wrapper.Board.invitee.val = "me";
            wrapper.Board.name.val = "john";
            wrapper.Board.owner.val = "john....too";
            wrapper.Board.owner_white.val = true;
            wrapper.Board.size.val = "2x2";
            wrapper.Board.status.val = "ok";
            
            
            TextWriter textWriter;
            textWriter = new StreamWriter(@"C:\Documents and Settings\info_seb\Bureau\testgetboard.xml");
            String ret = Save(wrapper);
            textWriter.Write(ret);
            textWriter.Close();
            return ret;
        }


                
    
        //this save return the XML in a string and can be displayed in the console,but BOM problem(don't seems to be a real problem)
        public static string Save(goimerir wrapper)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(goimerir));
            string serializedObject = string.Empty;
            using (MemoryStream stream = new MemoryStream())
            {
                serializer.Serialize(stream, wrapper);
                stream.Position = 0;
                using (StreamReader reader = new StreamReader(stream))
                {
                    serializedObject = reader.ReadToEnd();
                }
            }
              
            //MemoryStream stream = new MemoryStream();
            //serializer.Serialize(stream, wrapper);
           // byte[] b = stream.ToArray();
            //serializedObject = System.Text.Encoding.UTF8.GetString(b);

            return serializedObject;
        }
        
      
       
        /*
        //this save write directly into a file
        public static string Save(goimerir wrapper)
       {
           XmlSerializer serializer = new XmlSerializer(typeof(goimerir));

           TextWriter textWriter = new StreamWriter(@"C:\Documents and Settings\ssuner\Bureau\testgoo.xml");
           serializer.Serialize(textWriter, wrapper);
           string serializedObject = textWriter.ToString();
           //Console.WriteLine(textWriter.ToString());
           
           textWriter.Close();
     
           return serializedObject;
       }*/
        

     
      
        //this save return a string with the correct encoding(but no more line return)
        /*public static string Save(goimerir wrapper)
       {
            XmlSerializer ser = new XmlSerializer(typeof(goimerir));

            MemoryStream memStream= new MemoryStream();
            XmlTextWriter xmlWriter= new XmlTextWriter(memStream, Encoding.UTF8);
            xmlWriter.Namespaces = true;
            ser.Serialize(xmlWriter, wrapper);

            xmlWriter.Close();
            memStream.Close();
            string xml = Encoding.UTF8.GetString(memStream.GetBuffer());
            xml = xml.Substring(xml.IndexOf(Convert.ToChar(60)));
            xml = xml.Substring(0, (xml.LastIndexOf(Convert.ToChar(62)) + 1));
            return xml;


       }*/

        //check the server and if there is a response save the url of the server
        public String CheckConfig(String _URL)
        {
            String ret;
            try
            {
                ret = HttpGet(_URL);
                server = _URL;
            }
            catch (Exception e) { ret = "-1"; Console.WriteLine(e); }

            
            return ret;
        }
        



        //method with parameters
        public String CreateUser(String _name, String _screenname, String _password){


            var wrapper = new VersionPostUsers();
            wrapper.user_create = new User_Create();
            wrapper.user_create.fullname.val = _name;
            wrapper.user_create.screenname.val = _screenname;
            wrapper.user_create.password.val = _password;
            String ret = Save(wrapper);

            try
            {
                ret = HttpPost(server + "/users/", ret);
            }
            catch (Exception e) { ret = "-1"; Console.WriteLine(e); }
            
            return ret;
        }

        //method using the Client class attributes
        public String CreateUser()
        {


            var wrapper = new VersionPostUsers();
            wrapper.user_create = new User_Create();
            wrapper.user_create.fullname.val = username;
            wrapper.user_create.screenname.val = screenname;
            wrapper.user_create.password.val = password;
            String ret = Save(wrapper);
            

            try
            {
                ret = HttpPost(server + "/users/", ret);
            }
            catch (Exception e) { ret = "-1"; Console.WriteLine(e); }

            return ret;
        }


      

       
        public String ListUsers()
        {
            String ret;
            try
            {
                ret = HttpGet(server + "/users/");
            }
            catch (Exception e) { ret = "-1"; Console.WriteLine(e); }
           

            return ret;
        }

        public String CreateBoard(String _name,String _owner,String _invitee, String _size, bool _white)
        {

            var wrapper = new VersionCreateBoard();
            wrapper.create_board = new Create_Board();
            wrapper.create_board.name.val = _name;
            wrapper.create_board.owner.val = _owner;
            wrapper.create_board.invitee.val = _invitee;
            wrapper.create_board.size.val = _size;
            wrapper.create_board.owner_white.val = _white;
            String ret = Save(wrapper);

            try
            {
                ret = HttpPost(server + "/boards/", ret);
            }
            catch (Exception e) { ret = "-1"; Console.WriteLine(e); }

            

            return ret;

                       
        }

        public String CreateBoard(String _name, String _invitee, String _size, bool _white)
        {

            var wrapper = new VersionCreateBoard();
            wrapper.create_board = new Create_Board();
            wrapper.create_board.name.val = _name;
            wrapper.create_board.owner.val = username;
            wrapper.create_board.invitee.val = _invitee;
            wrapper.create_board.size.val = _size;
            wrapper.create_board.owner_white.val = _white;
            String ret = Save(wrapper);
            Console.WriteLine("create board\n");
            Console.WriteLine(ret);

             try
            {
                ret = HttpPost(server + "/boards/", ret);
            }
                catch (Exception e) { ret = "-1";Console.WriteLine(e); }

            return ret;


        }

        public String RetrieveBoards(){

            String ret;
             try
            {
                ret = HttpGet(server + "/boards/");
            }
             catch (Exception e) { ret = "-1"; Console.WriteLine(e); }
            return ret;
        }

        public String Invite(String _URL,String name)
        {
            var wrapper = new VersionCreateInvite();
            wrapper.create_invite = new Create_Invite();
            wrapper.create_invite.board.val = _URL;
            String ret = Save(wrapper);

             try
           {
               ret = HttpPost(server + "/users/"+name+"/invites/", ret);
           }
             catch (Exception e) { ret = "-1"; Console.WriteLine(e); }

            return ret;
        }

        public String Request(String _board)
        {
            var wrapper = new VersionBoardRequest();
            wrapper.create_board_request = new Create_Board_Request();
            wrapper.create_board_request.sender.val = username;
            String ret = Save(wrapper);

            try
            {
                ret = HttpPost(server + "/boards/" + _board + "/requests/", ret);
            }
            catch (Exception e) { ret = "-1"; Console.WriteLine(e); }

            return ret;
        }

        public String delete(String _board)
        {
            String ret;
            try
            {
                ret = HttpDelete(server + "/boards/" + _board);
            }
            catch (Exception e) { ret = "-1"; Console.WriteLine(e); }

            return ret;

        }

        public String GetBoard(String _board){

            String ret;
            try
            {
                ret = HttpGet(server + "/boards/"+_board);
            }
            catch (Exception e) { ret = "-1"; Console.WriteLine(e); }
            return ret;
        }


        // the skipping move is row=null and column=null
        public String Move(int _row, int _column,String _board)
        {
            var wrapper = new VersionMove();
            wrapper.create_move = new Create_Move();
            wrapper.create_move.row.val = _row;
            wrapper.create_move.column.val = _column;
            String ret = Save(wrapper);


            try
            {
                ret = HttpPost(server + "/boards/" + _board + "/moves/", ret);
            }
            catch (Exception e) { ret = "-1"; Console.WriteLine(e); }

            
            return ret;
        }



        public String GetMoves(String _board)
        {
            String ret;
            try
            {
                ret = HttpGet(server + "/boards/" + _board+"/moves/");
            }
            catch (Exception e) { ret = "-1"; Console.WriteLine(e); }


            return ret;

            
        }








       /* public string HttpPost(string URI, string Parameters)
        {
            System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
            //req.Proxy = new System.Net.WebProxy(ProxyString, true);

            req.ContentType = "application/x-www-form-urlencoded";
            req.Method = "POST";

            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
            req.ContentLength = bytes.Length;

            System.IO.Stream os = req.GetRequestStream();
            os.Write(bytes, 0, bytes.Length);
        
            os.Close();

            System.Net.WebResponse resp = req.GetResponse();
            if (resp == null) return null;

            System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
            return sr.ReadToEnd().Trim();
        }
        */

        
public  string HttpGet(string URI)
{
   System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
   //req.Proxy = new System.Net.WebProxy(ProxyString, true); //true means no proxy
   System.Net.WebResponse resp = req.GetResponse();
   System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
   return sr.ReadToEnd().Trim();
}

public string HttpDelete(string URI)
{
    System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
    
    req.Method = "DELETE";

    System.Net.WebResponse resp = req.GetResponse();
    if (resp == null) return null;
    System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
    return sr.ReadToEnd().Trim();

}


//using the http protocol
public  string HttpPost(string URI, string Parameters)
{
    
    System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
   //req.Proxy = new System.Net.WebProxy(ProxyString, true);
   //Add these, as we're doing a POST
   req.ContentType = "application/x-www-form-urlencoded";
   req.Method = "POST";
   
   //We need to count how many bytes we're sending. Post'ed Faked Forms should be name=value&
   byte [] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
   req.ContentLength = bytes.Length;
   System.IO.Stream os = req.GetRequestStream ();
   os.Write (bytes, 0, bytes.Length); //Push it out there
   os.Close ();
   Console.WriteLine("g envoyé  et j'attend...");
   System.Net.WebResponse resp = req.GetResponse();
   Console.WriteLine(" reponse recue...");
   if (resp== null) return null;
    System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
   return sr.ReadToEnd().Trim();
}
        

               

}

    
    
   

}
